# -*- coding: utf-8 -*-

from flask import Flask, g, session, request

from google.appengine.api.namespace_manager import set_namespace
from google.appengine.api import users

from dicthash.decorators import login_required_decor_factory
from dicthash.utils import Bunch

from .blueprints.lenta.code import register as register_lenta
from .blueprints.user.code import register as register_user
from .blueprints.auth.code import register as register_auth

from . import views_prototype as application_views


app = Flask(__name__)
app.config.update(
    SECRET_KEY = "12345"
)

#########################
# configure application #
#########################

@app.before_request
def set_user():
    """ """
    user = users.get_current_user()
    if user:
        g.user = Bunch(name="dyatel", namespace="ebanashka")
        set_namespace("ebanashka")
    else:
        g.user = None
        set_namespace('')

    
@app.context_processor
def inject_into_template():
    """ """
    return {
        'c': {
            'lenta': Bunch(name=u"Срань Герань", id=100500, namespace="ebanashka"),
            'view_args': request.view_args ,
            'create_login_url': users.create_login_url,
            'create_logout_url': users.create_logout_url
        }
    }

#######################
# register blueprints #
#######################   

register_lenta(app, '/lenta',
    {
        'db_backend': {},
        'login_required': login_required_decor_factory(
                                lambda: g.user,
                                lambda: users.create_login_url('/')
                          )
    },
    prototype = True
)

register_user(app, '/user',
    {
        'user_name_validator': lambda name: True if name else False
    },
    prototype = True
)

register_auth(app, '/auth',
    {
        'user_class': object,
        'default_destination': '/',
        'session_key_name': 'user_data',
        'user_name_validator': lambda name: (name, None) if name else (None, 'name is invalid')
    },
    prototype = True
)

#####################################
# register application url handlers #
#####################################

app.add_url_rule('/', 'root', application_views.root_handler)